/*pmFWCFu5nhKkBzYmrkBakZnddnQy0ymp6BPxwXdcfc1jQUw7kDaucCA3ASGaIj2I*/
import { base, cardCache } from 'nc-lightapp-front';

import constants from '../../constants';
import { addTransitypeBtns } from '../../utils';

import ampub from 'ampub';
import fa from 'fa';
// import ampub from '../../../../ampub/common/collection/release';
// import fa from '../../../../common/collection/release';

const { components, utils } = ampub;
const { fa_components, fa_utils } = fa;

const { getMultiLangByID } = utils.multiLangUtils;
const { loginContext, getContext, loginContextKeys } = components.LoginContext;
const { createOprationColumn } = utils.cardUtils;
const {AMTooltip} = components;

const { addSearchAreaReferFilter, addHeadAreaReferFilter, addBodyReferFilter } = fa_components.ReferFilter;
const { CardLinkToBill } = fa_components.CardLinkToBillUtil;
const { getAreaItemFields } = fa_utils.metaUtil;

import { setBodyBtnsEnable } from './setStatus';

const assetAll = constants.AREA.CARD.ASSET_ALL;
const basicInfoForm = constants.AREA.CARD.BASIC_INFO_AREA;
const financeForm = constants.AREA.CARD.FINANCE_AREA;
const headOtherForm = constants.AREA.CARD.HEAD_OTHERAREA;
const usedept_tab = constants.AREA.CARD.USEDEPT_TAB;
const alter_tab = constants.AREA.CARD.ALTER_TAB;
const evaluate_tab = constants.AREA.CARD.EVALUATE_TAB;
const reduce_tab = constants.AREA.CARD.REDUCE_TAB;
const devalue_tab = constants.AREA.CARD.DEVALUE_TAB;
const deploy_tab = constants.AREA.CARD.DEPLOY_TAB;
const dep_tab = constants.AREA.CARD.DEP_TAB;
const subequip_tab = constants.AREA.CARD.SUBEQUIP_TAB;
const templateDataSource = constants.templateDataSource;
const assetDataSource = constants.assetDataSource;

//加载模板
export default function(props) {
	const that = this;
	const promise = new Promise(function(resolve, reject) {
		//从地址栏获取交易类型
		const transiType = that.props.getUrlParam('transiType');
		const pagecodeFromUrl = that.props.getSearchParam('p');//获取pagecode
		if (!transiType && !pagecodeFromUrl) {
			// console.log('------ 访问路径不正确');
			// console.log('------ 交易类型:', transiType);
			// console.log('------ 交易类型:', pagecodeFromUrl);
			reject();
			return;
		}
		const pagecode = transiType || pagecodeFromUrl;
		that.state.pageCode = pagecode;
		if (that.curr_transiType === transiType) {
			resolve();
			return;
		} else {
			//判断缓存中是否存在
			let templateCached = cardCache.getDefData(transiType, templateDataSource);
			if (templateCached) {
				let { button, meta } = templateCached;
				button = JSON.parse(button);
				meta = JSON.parse(meta);
				props.button.setButtons(button);
				modifierMeta.call(that, props, meta);
				initUI(that, meta);
				that.curr_transiType = transiType;
				that.templateid = meta.pageid;
				resolve();
				return;
			}
		}

		props.createUIDom(
			{
				pagecode //页面id
			},
			function(data) {
				if (data) {
					let metaCopy = {};
					if (data.context) {
						// 初始化上下文变量
						loginContext(data.context, assetDataSource);

						//初始化时获取后台数据源信息，并存在缓存中，用于卡片解锁
						getContext(loginContextKeys.dataSourceCode, assetDataSource);
					}
					if (data.button) {
						let button = data.button;
						//获取当前语种
						let currentLangSeq = getContext(loginContextKeys.languageIndex, assetDataSource);
						addTransitypeBtns.call(that, button, currentLangSeq);
						metaCopy.button = JSON.stringify(button);
						props.button.setButtons(button, () => {});
					}
					if (data.template) {
						let meta = data.template;
						that.templateid = meta.pageid;
						metaCopy.meta = JSON.stringify(meta);
						modifierMeta.call(that, props, meta);
						initUI(that, meta);
					}

					//缓存模板
					cardCache.setDefData(transiType, templateDataSource, metaCopy);
					that.curr_transiType = transiType;
					resolve();
				} else {
					reject();
				}
			}
		);
	});
	return promise;
}

//获取到 template 后初始化UI
function initUI(that, meta) {
	//默认显示浏览态按钮
	const browseBtns = constants.CARD_BROWER_BTNS;
	const editBtns = constants.CARD_EDIT_BTNS;
	that.props.button.setButtonVisible(browseBtns, true);
	that.props.button.setButtonVisible(editBtns, false);

	that.props.meta.setMeta(meta, () => {
		//获取各个区域的字段
		that.basicInfoFields = getAreaItemFields(that.props, basicInfoForm); //基本信息区域字段
		that.financeFields = getAreaItemFields(that.props, financeForm); //财务区域字段

		initState.call(that, meta);

		const status = that.props.getUrlParam('status');

		//默认收起的页签
		that.props.cardTable.toggleCardTable(constants.TabsHideDefault, false);

		//初始化缓存
		let pk2ClientKeyMap = cardCache.getDefData(constants.pk2ClientKeyMap, assetDataSource);
		if (!pk2ClientKeyMap) {
			cardCache.setDefData(constants.pk2ClientKeyMap, assetDataSource, {});
		}

		//从模板上获取可修订的字段
		let reviseFieldsFromTemplet = new Set();
		meta[basicInfoForm].items.map((item) => {
			if (item.isrevise) {
				reviseFieldsFromTemplet.add(item.attrcode);
			}
		});
		meta[financeForm].items.map((item) => {
			if (item.isrevise) {
				reviseFieldsFromTemplet.add(item.attrcode);
			}
		});
		meta[headOtherForm].items.map((item) => {
			if (item.isrevise) {
				reviseFieldsFromTemplet.add(item.attrcode);
			}
		});
		that.reviseFields = [ ...reviseFieldsFromTemplet ].filter((f) => {
			return constants.FIELDS.REVISE_FIELDS.includes(f) || f.startsWith(constants.FIELDS.DEF_FIELD);
		});

		setTemplateDefautValue(that.props,meta);
	});
}

//模板修改
function modifierMeta(props, meta) {
	const that = this;
	//添加复制卡片对话框模板
	this.facardCopy.initCopyCardTemplate(meta);
	//添加参照过滤
	addHeadAreaReferFilter(props, meta, constants.ReferFilterConfig);
	addBodyReferFilter(props, meta, constants.ReferFilterConfig);

	//删除本不属于 gridrelation 中的区域
	delete meta['gridrelation'][assetAll];

	let status = props.getUrlParam('status');

	meta[basicInfoForm].items.map((item) => {
		// 资产类别
		if (item.attrcode === 'pk_category') {
			item.onlyLeafCanSelect = true;
			item.queryCondition = () => {
				let pk_org = props.form.getFormItemsValue(basicInfoForm, 'pk_org');
				pk_org = pk_org && pk_org.value;
				return {
					pk_org,
					transi_type: that.state.pageCode
				};
			};
		}

		// 管理部门 是否允许选择非末级
		if (item.attrcode === 'pk_mandept' || item.attrcode === 'pk_mandept_v') {
			item.onlyLeafCanSelect = !that.is_allow_dept_midlev;
		}
		// 使用部门 是否允许选择非末级
		if (item.attrcode === 'pk_usedept' || item.attrcode === 'pk_usedept_v') {
			item.onlyLeafCanSelect = !that.is_allow_dept_midlev;
		}
		//使用状况、增加方式只能选择末级
		if (item.attrcode === 'pk_addreducestyle' || item.attrcode === 'pk_usingstatus') {
			item.onlyLeafCanSelect = true;
		}
	});

	//附属设备 表体添加操作列
	let oprCol = createOprationColumn(props, {
		tableId: subequip_tab,
		areaId: 'card_body_inner',
		getInnerBtns: (props, text, record, index) => {
			let status = props.getUrlParam('status');
			if (status === constants.UISTATE.BROWSE) {
				return [];
			} else {
				return Object.values(constants.CARD_BTNS.TABLE_BODY.SUBEQUIP_TAB);
			}
		},
		tableButtonClick: (props, key, text, record, index, tableId) => {
			subequipTab_tableButtonClick(props, key, text, record, index, 'card_body_inner');
		}
	});
	meta[subequip_tab].items.push(oprCol);

	//多使用部门 表体添加操作列
	let oprCol1 = createOprationColumn(props, {
		tableId: usedept_tab,
		areaId: 'card_body_inner1',
		getInnerBtns: (props, text, record, index) => {
			let status = props.getUrlParam('status');
			if (status === constants.UISTATE.BROWSE) {
				return [];
			} else {
				return Object.values(constants.CARD_BTNS.TABLE_BODY.USEDEPT_TAB);
			}
		},
		tableButtonClick: (props, key, text, record, index, tableId) => {
			usedeptTab_tableButtonClick(props, key, text, record, index, 'card_body_inner1');
		}
	});
	meta[usedept_tab].items.push(oprCol1);

	//减值记录 bill_code 添加超链
	meta[devalue_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'bill_code') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill.value, 'HQ');
								}}
							>
								{record.values.bill_code && record.values.bill_code.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//调拨记录 bill_code_out（调出单号） 添加超链
	meta[deploy_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'bill_code_out') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill.value, 'HC');
								}}
							>
								{record.values.bill_code_out && record.values.bill_code_out.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
		if (item.attrcode == 'bill_code_in') {
			//调入
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill_in.value, 'HD');
								}}
							>
								{record.values.bill_code_in && record.values.bill_code_in.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//评估记录 bill_code（评估单号） 添加超链
	meta[evaluate_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'bill_code') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill.value, 'HE');
								}}
							>
								{record.values.bill_code && record.values.bill_code.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//变动记录 bill_code（变动单号） 添加超链
	meta[alter_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'bill_code') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(that, props, record.values.pk_bill.value, 'HG');
								}}
							>
								{record.values.bill_code && record.values.bill_code.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//减少记录 reducesource（减少来源） 添加超链
	meta[reduce_tab].items.map((item, key) => {
		//单据号添加下划线超链接
		if (item.attrcode == 'reducesource') {
			item.renderStatus = 'browse';
			item.render = (text, record, index) => {
				return (
					<div className="card-table-td">
						<AMTooltip nodeType="cardTable">
							<span
								className="code-detail-link"
								onClick={() => {
									CardLinkToBill.call(
										that,
										props,
										record.values.pk_bill.value,
										record.values.bill_type.value
									);
								}}
							>
								{record.values.reducesource && record.values.reducesource.value}
							</span>
						</AMTooltip>
					</div>
				);
			};
		}
	});

	//多使用部门
	meta[usedept_tab].items.map((item, key) => {
		if (item.attrcode == 'pk_dept' || item.attrcode == 'pk_dept_v') {
			item.onlyLeafCanSelect = !that.is_allow_dept_midlev;
			item.isMultiSelectedEnabled = true;
		}
	});

	return meta;
}

//附属设备表体操作列事件
const subequipTab_tableButtonClick = (props, key, text, record, index) => {
	switch (key) {
		case constants.CARD_BTNS.TABLE_BODY.SUBEQUIP_TAB.DELETE_LINE:
			props.cardTable.delRowsByIndex(subequip_tab, index);
			setBodyBtnsEnable(props, subequip_tab);

			break;
		default:
			break;
	}
};

//多使用部门表体操作列事件
const usedeptTab_tableButtonClick = (props, key, text, record, index) => {
	switch (key) {
		case constants.CARD_BTNS.TABLE_BODY.USEDEPT_TAB.DELETE_LINE:
			props.cardTable.delRowsByIndex(usedept_tab, index);
			setBodyBtnsEnable(props, usedept_tab);

			break;
		default:
			break;
	}
};

//初始化 state 中的参数
function initState(meta) {
	if (meta[basicInfoForm]) {
		//获取模板上使用部门、管理部门是否可以为空
		let items = meta[basicInfoForm].items;
		for (let i = 0; i < items.length; i++) {
			let item = items[i];
			if (item.attrcode === constants.FIELDS.PK_USEDEPT) {
				this.state.usedeptIsNotNull = !!item.required;
			} else if (item.attrcode === constants.FIELDS.PK_MANDEPT) {
				this.state.mandeptIsNotNull = !!item.required;
			}
		}
	}
}

//将模板默认值设置到界面上
function setTemplateDefautValue(props, meta) {
	let defaultValue = {
		[basicInfoForm]: {}
	};
	meta[basicInfoForm].items.map((item) => {
		if (item.initialvalue && item.initialvalue) {
			defaultValue[basicInfoForm][item.attrcode] = item.initialvalue;
		}
	});
	props.form.setFormItemsValue(basicInfoForm, defaultValue[basicInfoForm]);
}

/*pmFWCFu5nhKkBzYmrkBakZnddnQy0ymp6BPxwXdcfc1jQUw7kDaucCA3ASGaIj2I*/